<?php

/**
 * Subclass for representing a row from the 'tag' table.
 *
 * 
 *
 * @package lib.model
 */ 
class Tag extends BaseTag
{
    /**
     * 
     * @desc Returns array of ids tags by Slug_name. if user nick set, return tags for one user
     * @param string $slugName
     * @param string $userNick
     */
    public static function getIdsByTag($slugName, $userNick = '' )
    {
        if( $userNick != '' )
        {
            $userId = User::getIdByNick($userNick);
            $query = 'SELECT
                    tag.id
                FROM tag
                WHERE tag.slug_name like "' . $slugName . '"
                and tag.user_id = ' . $userId . '
                and tag.status_id = ' . MyConstants::STATUS_APPROVED;
        }else 
        {
            $query = 'SELECT
                    tag.id
                FROM tag
                WHERE tag.slug_name like "' . $slugName . '"
                and tag.status_id = ' . MyConstants::STATUS_APPROVED;
        }
        $stmt = Propel::getConnection()->prepareStatement($query);
        $rs = $stmt->executeQuery();

        $arSearchIds = array();


        // Search for first image
        while( $rs->next() )
        {
            $arSearchIds[$rs->getInt('id')] = $rs->getInt('id');
        }
        return $arSearchIds;
    }
    /**
     * 
     * Tags by user id, sorted by priority
     * @param int $id
     */
    public static function getActivePostsByUser( $id )
    {
        $c = new Criteria();
        $c->add(TagPeer::STATUS_ID, MyConstants::STATUS_APPROVED);
        $c->add(TagPeer::USER_ID, $id);
        $c->addDescendingOrderByColumn(TagPeer::PRIORITY);
        return $arBlogs = TagPeer::doSelect($c);
    }
    public static function addBlogsInfo($id, $blogId)
    {
        /* @var $tag Tag */
        $tag = TagPeer::retrieveByPK($id);
        if( $tag )
        {
            $arIds = array();
            $arIds = explode(',', $tag->getBlogsIdsCsv());
            foreach( $arIds as $key => $id )
            {
                if( ($id == $blogId ) || ($id == 0) )
                {
                    unset($arIds[$key]);
                }
            }
            $arIds[] = $blogId;
            $tag->setBlogsIdsCsv(join(',',$arIds));
            $tag->setBlogsQnt(count($arIds));
            $tag->save();
        }
    }
    public static function removeBlogsInfo($id, $blogId)
    {
        /* @var $tag Tag */
        $tag = TagPeer::retrieveByPK($id);
        if( $tag )
        {
            $arIds = explode(',', $tag->getBlogsIdsCsv());
            $arIds = array_diff($arIds, array($blogId, 0));
            $ids = join(',',$arIds);
            $tag->setBlogsIdsCsv($ids);
            $tag->setBlogsQnt(count($arIds));
            $tag->save();
        }
    }
}
